<template>
  <div>
    <CategorySelector :disabled="!isListView"></CategorySelector>

    <el-card shadow="hover" style="margin-top: 20px">
      <div v-if="isListView">
        <el-button type="primary" icon="ele-Plus" :disabled="!category3Id"
          @click="showAddOrEditViewHandler()">添加属性</el-button>

        <el-table style="margin-top: 20px" border stripe :data="attrs">
          <el-table-column label="序号" type="index"></el-table-column>
          <el-table-column label="属性名称" prop="attrName"></el-table-column>
          <el-table-column label="属性值名称列表">
            <template #="{ row }">
              <el-tag v-for="attrValue in row.attrValueList" :key="attrValue.id" type="success"
                style="margin-right: 5px">{{ attrValue.valueName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column>
            <template #="{ row }">
              <el-button type="warning" icon="ele-Edit" @click="showAddOrEditViewHandler(row)"></el-button>
              <el-popconfirm title="你确定要删除吗" @confirm="confirmDeleteAttrHandler(row.id)">
                <template #reference>
                  <el-button type="danger" icon="ele-Delete"></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>

      </div>
      <div v-else>
        <el-form inline>
          <el-form-item label="属性名">
            <el-input v-model="formData!.attrName" @blur="enterAttrNameHandler"
              @keydown.enter="enterAttrNameHandler"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :disabled="!formData!.attrName" @click="addAttrValueHandler">添加属性值</el-button>
            <el-button @click="isListView = true">取消</el-button>
          </el-form-item>
        </el-form>
        <el-table :data="formData!.attrValueList">
          <el-table-column label="序号" type="index"></el-table-column>
          <el-table-column label="属性值名称">
            <template #="{ row }">
              <span style="display: inline-block; width: 100%;" v-if="!row.isEdit"
                @dblclick="changeInputStatusHandler(row)">{{ row.valueName }}</span>
              <el-input v-else ref="attrValueInputRef" v-model="inputAttrValue" @blur="enterNewAttrValueHandler(row)"
                @keydown.enter="enterNewAttrValueHandler(row)"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #="{ row }">
              <el-button type="danger" icon="ele-Delete" @click="deleteAttrValuehandler(row)"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <div>
          <el-button type="primary" :disabled="!(formData!.attrName && formData!.attrValueList.length > 0)"
            @click="saveAttrHandler">保存</el-button>
          <el-button @click="isListView = true">取消</el-button>
        </div>
      </div>
    </el-card>

  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "ProductAttrIndex",
});
</script>

<script lang="ts" setup>
import CategorySelector from '@/components/CategorySelector/index.vue'
import { watch, ref, nextTick } from "vue";
import useCategorySelector from "@/hooks/categorySelector";
import { requestAttrInfoList, requestSaveAttrInfo } from "@/api/attr";
import { ElMessage, type ElInput } from 'element-plus';
import type { ResAttr, ReqSaveAttr, ReqSaveAttrValue } from "@/api/attr";
// 这种引入的效率要比 import _ from "lodash" 的效率高得多 因为下面得方式是按需引入
import cloneDeep from "lodash/cloneDeep"

const { category1Id, category2Id, category3Id } = useCategorySelector();

// 存储所有的属性列表数据
const attrs = ref<ResAttr[]>([]);
// 记录当前显示的视图
const isListView = ref(true)
// 收集用户输入的数据
const formData = ref<ReqSaveAttr | null>(null)
// 获取属性值的实例对象
const attrValueInputRef = ref<typeof ElInput | null>(null);
// 绑定收集用户在属性值列表输入框中输入的数据
const inputAttrValue = ref("")

async function getAttrs() {
  if (category3Id.value != "") {
    try {
      attrs.value = await requestAttrInfoList(
        Number(category1Id.value),
        Number(category2Id.value),
        Number(category3Id.value)
      );
      // console.log(attrs);
    } catch (e) { }
  }
}

watch(category3Id, getAttrs);

// 点击添加按钮
function showAddOrEditViewHandler(row?: ResAttr) {
  // 切换到添加视图
  isListView.value = false;
  if (row) {
    // 编辑 对formData初始化
    formData.value = cloneDeep(row)
    // formData.value = JSON.parse(JSON.stringify(row))
  } else {
    // 添加 对formData进行初始化
    formData.value = {
      categoryId: Number(category3Id.value),
      categoryLevel: 3,
      attrName: "",
      attrValueList: []
    }
  }
}

// 检测要添加的属性名称是否存在
function enterAttrNameHandler() {
  if (formData.value) {
    // 过滤掉当前这条数据
    const filterAttrs = attrs.value.filter(
      item => item.id != formData.value!.id
    )
    const isExists = filterAttrs.find(
      item => item.attrName == formData.value?.attrName
    )
    if (isExists) {
      ElMessage.error("已经存在同名的属性");
      formData.value.attrName = ""
    }
  }
}

// 给指定的属性名添加属性值
function addAttrValueHandler() {
  formData.value?.attrValueList.push({
    valueName: "",
    isEdit: true
  })
  nextTick(() => {
    attrValueInputRef.value?.focus()
  })
}

// 确认输入的属性值
function enterNewAttrValueHandler(row: ReqSaveAttrValue) {
  // 判断当前值是否为空
  const newValue = inputAttrValue.value.trim();

  if (!row.isEdit && newValue == "") {
    return;
  }

  if (newValue == "") {
    // 如果用户没有输入任何内容，则表示放弃这次添加
    // 也就是从 formData.value.attrValueList 删除 row
    if (formData.value) {
      formData.value.attrValueList = formData.value.attrValueList.filter(
        item => item != row
      )
    }
    // inputAttrValue.value = "";
  } else {
    const isExists = formData.value?.attrValueList.find(
      (item) => item.valueName == newValue && item != row
    )
    if (isExists) {
      inputAttrValue.value = "";
      ElMessage.error("已经存在该值")
      nextTick(() => {
        attrValueInputRef.value?.focus()
      })
    } else {
      // 如果用户输入了内容，则把这个输入内容添加到当前row的valueName属性
      row.valueName = newValue;
      // 把编辑状态修改为显示的状态
      row.isEdit = false;
      // 清空inputAttrValue中存储的值
      inputAttrValue.value = "";
    }
  }
}

// 点击span进入编辑状态
function changeInputStatusHandler(row: ReqSaveAttrValue) {
  row.isEdit = true;
  inputAttrValue.value = row.valueName;
  nextTick(() => {
    attrValueInputRef.value?.focus()
  })
}

// 点击删除按钮删除指定的属性值
function deleteAttrValuehandler(row: ReqSaveAttrValue) {
  if (formData.value) {
    formData.value.attrValueList = formData.value?.attrValueList.filter(
      item => item != row
    )
  }
}

// 提交保存
async function saveAttrHandler() {
  if (formData.value) {
    const messageType = formData.value.id ? "修改" : "添加"
    try {
      await requestSaveAttrInfo(formData.value);
      ElMessage.success(`${messageType}"成功"`);
      isListView.value = true;
      getAttrs()
    } catch (e) {
      ElMessage.error(`${messageType}"失败"`);
    }
  }
}

// 删除attr
function confirmDeleteAttrHandler(id: number) {
}

</script>


<style scoped></style>
